const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const serve = require('koa-static');
const logger = require('koa-logger');
const path = require('path');

const config = require('./config/config');
const { setupLogger } = require('./utils/logger');
const dataService = require('./services/dataService');
const schedulerService = require('./services/schedulerService');
const apiController = require('./controllers/apiController');

// 初始化应用
const app = new Koa();
const router = new Router();

// 设置日志
const appLogger = setupLogger();

// 中间件
app.use(logger());
app.use(cors({
  origin: '*',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  headers: ['Content-Type', 'Authorization', 'Accept']
}));
app.use(bodyParser());
app.use(serve(path.join(__dirname, '../public')));

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = {
      success: false,
      error: err.message || '内部服务器错误'
    };
    appLogger.error('请求处理错误:', err);
  }
});

// API路由
// 基础路由
router.get('/api/health', apiController.health.bind(apiController));
router.get('/api/summary', apiController.getSummary.bind(apiController));
router.get('/api/stats', apiController.getStats.bind(apiController));

// 代币相关路由
router.get('/api/tokens', apiController.getTokens.bind(apiController));
router.get('/api/tokens/:symbol', apiController.getTokenDetail.bind(apiController));

// 聪明钱相关路由
router.get('/api/smart-money', apiController.getSmartMoney.bind(apiController));
router.get('/api/smart-money/:address', apiController.getSmartMoneyDetail.bind(apiController));

// 市场数据路由
router.get('/api/market-data', apiController.getMarketData.bind(apiController));

// 趋势分析路由
router.get('/api/trends', apiController.getTrends.bind(apiController));

// 风险分析路由
router.get('/api/risks', apiController.getRisks.bind(apiController));

// 搜索路由
router.get('/api/search', apiController.search.bind(apiController));

// 数据管理路由
router.post('/api/refresh', apiController.refreshData.bind(apiController));
router.get('/api/files/stats', apiController.getFileStats.bind(apiController));
router.get('/api/files/download/:type', apiController.downloadFile.bind(apiController));

// 兼容旧版API
router.get('/api/data', async (ctx) => {
  const { source, limit = 100, offset = 0, filter } = ctx.query;
  
  // 重定向到新的API
  if (source === 'tokens') {
    await apiController.getTokens(ctx);
  } else if (source === 'smartMoney') {
    await apiController.getSmartMoney(ctx);
  } else {
    // 返回概览数据
    await apiController.getSummary(ctx);
  }
});

// 主页路由
router.get('/', async (ctx) => {
  ctx.redirect('/index.html');
});

// API文档路由
router.get('/api', async (ctx) => {
  ctx.body = {
    name: 'Crypto Aggregator API',
    version: '1.0.0',
    description: '加密货币信息聚合和分析系统API',
    endpoints: {
      health: 'GET /api/health - 健康检查',
      summary: 'GET /api/summary - 数据概览',
      stats: 'GET /api/stats - 统计信息',
      tokens: {
        list: 'GET /api/tokens - 获取代币列表',
        detail: 'GET /api/tokens/:symbol - 获取代币详情'
      },
      smartMoney: {
        list: 'GET /api/smart-money - 获取聪明钱列表',
        detail: 'GET /api/smart-money/:address - 获取聪明钱详情'
      },
      marketData: 'GET /api/market-data - 获取市场数据',
      trends: 'GET /api/trends - 获取趋势分析',
      risks: 'GET /api/risks - 获取风险分析',
      search: 'GET /api/search?q=keyword - 搜索',
      refresh: 'POST /api/refresh - 刷新数据',
      files: {
        stats: 'GET /api/files/stats - 文件统计',
        download: 'GET /api/files/download/:type - 下载文件 (json|excel|compact)'
      }
    },
    parameters: {
      tokens: {
        symbol: '代币符号过滤',
        category: '分类过滤 (large_cap|mid_cap|small_cap|micro_cap)',
        minScore: '最小评分 (0-100)',
        maxScore: '最大评分 (0-100)',
        sortBy: '排序字段 (score|avgPrice|avgVolume24h|avgMarketCap)',
        order: '排序方向 (asc|desc)',
        limit: '返回数量限制',
        offset: '偏移量'
      },
      smartMoney: {
        minScore: '最小智能评分 (0-100)',
        maxScore: '最大智能评分 (0-100)',
        riskLevel: '风险等级 (low|medium|high|very_high)',
        tags: '标签过滤 (逗号分隔)',
        sortBy: '排序字段 (smartScore|avgPnl7d|avgPnl30d)',
        order: '排序方向 (asc|desc)',
        limit: '返回数量限制',
        offset: '偏移量'
      },
      risks: {
        severity: '严重程度 (low|medium|high|critical)',
        type: '风险类型'
      },
      search: {
        q: '搜索关键词 (至少2个字符)',
        type: '搜索类型 (all|tokens|smartMoney)',
        limit: '返回数量限制'
      }
    },
    examples: {
      getTopTokens: '/api/tokens?sortBy=score&order=desc&limit=10',
      searchBitcoin: '/api/search?q=bitcoin&type=tokens',
      getHighRiskTokens: '/api/risks?severity=high',
      getSmartWhales: '/api/smart-money?tags=whale&sortBy=smartScore&order=desc'
    }
  };
});

// 使用路由
app.use(router.routes());
app.use(router.allowedMethods());

// 错误处理
app.on('error', (err, ctx) => {
  appLogger.error('应用错误:', err);
});

// 启动服务器
const startServer = async () => {
  try {
    // 初始化数据服务
    await dataService.initialize();
    
    // 启动定时任务
    schedulerService.start();
    
    // 启动HTTP服务器
    app.listen(config.server.port, config.server.host, () => {
      appLogger.info(`服务器启动成功，监听端口: ${config.server.port}`);
      console.log(`🚀 服务器运行在 http://${config.server.host}:${config.server.port}`);
      console.log(`📊 API文档: http://${config.server.host}:${config.server.port}/api`);
      console.log(`🌐 Web界面: http://${config.server.host}:${config.server.port}`);
    });
  } catch (error) {
    appLogger.error('服务器启动失败:', error);
    process.exit(1);
  }
};

// 优雅关闭
process.on('SIGTERM', () => {
  appLogger.info('收到SIGTERM信号，正在关闭服务器...');
  schedulerService.stop();
  process.exit(0);
});

process.on('SIGINT', () => {
  appLogger.info('收到SIGINT信号，正在关闭服务器...');
  schedulerService.stop();
  process.exit(0);
});

// 启动应用
startServer();

module.exports = app;

